package com.crl.rcdp.gateway.filter;

import com.cars.util.global.AuthTypeEnum;
import com.cars.util.jwt.JwtUtil;
import com.cars.util.string.StringUtil;
import org.apache.commons.lang3.StringUtils;

import java.net.URI;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/7/15 23:44
 */
public class FilterUtil {

    /**
     * 处理授权方式
     *
     * @param authorization
     * @param appid
     * @return
     */
    public static int getAuthType(String authorization, String accessToken, String appid) {
        int authType = 0;//授权方式 0：appid，1：password，2：无需权限的请求，3：appsecrect
        try {
            if (StringUtil.isNotNullOrEmpty(authorization)) {
                authType = AuthTypeEnum.PASSWORD.getValue();
            } else if (StringUtil.isNotNullOrEmpty(accessToken)) {
                authType = AuthTypeEnum.APPSECRECT.getValue();
            } else if (StringUtil.isNotNullOrEmpty(appid)) {
                authType = AuthTypeEnum.APPID.getValue();
            } else {
                authType = AuthTypeEnum.NOAUTH.getValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return authType;
    }

    /**
     * 所属owner
     *
     * @return
     */
    public static String getOwner(String authorization, String accessToken, String appid) {
        String owner = "";
        if (StringUtil.isNotNullOrEmpty(authorization)) {
            owner = JwtUtil.getJWTOwner(authorization);
        } else if (StringUtil.isNotNullOrEmpty(accessToken)) {
            owner = JwtUtil.getJWTOwner(accessToken);
        } else if (StringUtil.isNotNullOrEmpty(appid)) {
            owner = appid;
        } else {
            owner = "";
        }
        return owner;
    }


    private static final String URI_FIRST_SYMBOL = "/";

    /**
     * 处理url 以/ 开头
     *
     * @param str
     * @return
     */
    public static String formatUrl(String str) {
        if (StringUtils.isNotBlank(str) && StringUtils.indexOf(str, URI_FIRST_SYMBOL) < 0) {
            str = URI_FIRST_SYMBOL.concat(str);
        }
        return str;
    }

    /**
     * 获取uri  http+host+port
     *
     * @param uri
     * @return
     */
    public static String getUriAddress(URI uri) {
        return String.format("%s://%s:%s", uri.getScheme(), uri.getHost(), uri.getPort());
    }
}
